package com.willie.elasticjob.factory;

import com.dangdang.ddframe.job.api.ElasticJob;
import com.willie.elasticjob.util.BeanTools;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * <p>
 * SimpleJob工厂
 * </p>
 *
 * @author willie
 * @since 2018/11/21
 */
public abstract class AbstractElasticJobFactory {
    /**
     * 创建任务
     *
     * @param jobName 任务名称
     * @return 任务实例
     */
    public static <T extends ElasticJob> T createElasticJob(String jobName) {
        ElasticJob elasticJob = null;
        try {
            Class<? extends ElasticJob> jobClass = (Class<? extends ElasticJob>) Class.forName(jobName);
            elasticJob = jobClass.newInstance();
            Field[] declaredFields = jobClass.getDeclaredFields();
            if (declaredFields != null && declaredFields.length > 0) {
                initElastisJobProperties(declaredFields, elasticJob);
            }
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
        return (T) elasticJob;
    }

    /**
     * @param declaredFields 声明的方法
     * @param elasticJob     任务
     */
    private static void initElastisJobProperties(Field[] declaredFields, ElasticJob elasticJob) {
        try {
            for (Field field : declaredFields) {
                Annotation[] annotations = field.getAnnotations();
                if (annotations == null || annotations.length == 0) {
                    continue;
                }
                boolean flag = false;
                for (Annotation annotation : annotations) {
                    Class<? extends Annotation> annotationType = annotation.annotationType();
                    if (annotationType.equals(Resource.class) || annotationType.equals(Autowired.class)) {
                        flag = true;
                        break;
                    }
                }

                if (flag) {
                    field.setAccessible(true);
                    //从IOC容器中取出实例

                    field.set(elasticJob, BeanTools.getBean(field.getType()));

                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
